<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <textarea id="editor" cols="30" rows="10"></textarea>
</body>

</html>
<script type="module">
  import { adapter,backdone } from './command.mjs'
  const INPUT_TYPE = {
    INSERT: "insertText",
    DELETE: "deleteContentBackward",
    INSERT_PASTE: "insertFromPaste",
    DELETE_DRAG: "deleteByDrag",
    INSERT_DRAG: "insertFromDrop",
    DELETE_CUT: "deleteByCut",
    INERT_COMPOSITION: "insertCompositionText",
    LINE_BREAK: "insertLineBreak"
  }
  let doc = { cursor: 0}
  let editor = document.getElementById("editor")
  editor.oncompositionend = function (e) {
    let cursorPos = getCursorPos(editor);
    let index = cursorPos - e.data.length
    let body = e.data
    adapter.input(index, body)
  }
  editor.addEventListener('compositionend', editor.oncompositionend)
  editor.addEventListener('beforeinput', function(e){
    e.preventDefault()
    let index = getCursorPos(editor);
    if(e.inputType === INPUT_TYPE.INSERT){
      adapter.input(index, e.data)
      editor.value = editor.value.substring(0,index)+e.data+editor.value.substring(index)
      setCursorPos(editor,index+e.data.length)
    }
    
  })
  document.onkeydown = function (event) {
    var e = event || window.event || arguments.callee.caller.arguments[0];
    if (e.keyCode >= 37 && e.keyCode <= 40) {
      doc.cursor = getCursorPos(editor);
    }else if(e.keyCode === 27){
      let action = backdone()
      if(!action) return
      if(action.type === "input"){
        editor.value = editor.value.substring(0,action.index)+editor.value.substring(action.index+action.body.length)
      }
    }else if(e.keyCode === 8){
      let index = getCursorPos(editor);
      editor.value = editor.value.substring(0,index-1)+editor.value.substring(index)
      setCursorPos(editor,index-1)
    }
  }

  const getCursorPos = function (element) {
    return element.selectionStart
  }
  const setCursorPos = function (element, pos) {
    if (element.setSelectionRange) {
      element.setSelectionRange(pos, pos)
    } else if (element.createTextRange) {
      let range = element.createTextRange()
      range.collapse(true)
      range.moveEnd('character', pos)
      range.moveStart('charecter', pos)
      range.select()
    }
  }
</script>